package com.stx.sanbu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.stx.sanbu.dao.UserDao;
import com.stx.sanbu.entity.User;

import flexjson.JSONSerializer;

/**
 * 用户注册的Servlet
 */
public class RegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegistServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		User user = new User();
		UserDao dao = new UserDao();
		user.setUs_name(request.getParameter("name"));
		user.setUs_password(request.getParameter("password"));
		try {
			switch (Integer.parseInt(request.getParameter("state"))) {
			case 0:// 注册校验
				System.out.println("我在这里！" + user.getUs_name());
				response.setCharacterEncoding("utf-8");
				PrintWriter out = response.getWriter();
				out.print(dao.isOk(user)?"可以注册！":"用户名已经存在！");
				out.flush();
				out.close();
				break;
			case 1:
				if (dao.insertUser(user)) {// 注册成功时
					request.setAttribute("message", "注册成功，请登录！");
					getServletContext().getRequestDispatcher("/JSP/Login.jsp")// 跳转到登录页面
							.forward(request, response);
				}
				break;
			}

		} catch (SQLException e) {
			request.setAttribute("message", "注册失败，请重新注册！");
			getServletContext().getRequestDispatcher("/JSP/Regist.jsp")// 跳转到登录页面
					.forward(request, response);
			e.printStackTrace();
		}
	}

}
